<?php

namespace App\Http\Controllers\api;

use App\Common\ApiReturn;
use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\Attention;
use App\Models\BalanceLog;
use App\Models\Car;
use App\Models\CommodityOrder;
use App\Models\Coupon;
use App\Models\CustomerSessionInfo;
use App\Models\GroupBuy;
use App\Models\Gzh\Pay;
use App\Models\Image;
use App\Models\PasswordLog;
use App\Models\ServiceAppointment;
use App\Models\User;
use App\Models\UserCoupon;
use App\Models\VerificationCode;
use App\Repository\CommodityRepository;
use App\Service\IndexService;
use App\Service\ShopService;
use App\Service\SmsService;
use App\Service\WechatService;
use GuzzleHttp\Client;
use http\Client\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use PHPUnit\Framework\Constraint\Count;

class UserController extends Controller
{
    public $request, $shopService, $indexService;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->request = $request;
    }

    /**
     * 新版登录接口，只通过code获取用户信息，不进行ENCRYPTED DATA解密
     * @param Request $request
     * @return array
     */
    public function login(Request $request)
    {
        try {
            $wechat = app('wechat');
            $code = $request->header('X-WX-Code');

            if (empty($code)) {
                throw new \Exception('请求头中未包含：X-WX-Code');
            }
            app('log')->debug('code: ' . var_export($code, true));

            $sessionInfo = $wechat->auth->session($code);
            app('log')->debug('session: ' . var_export($sessionInfo, true));
            // 4. 储存到数据库中
            $userResult = CustomerSessionInfo::storeUserInfo2($sessionInfo);
            $res = $userResult['model'];


            // 组装诚小程序的格式
            $data = [
                'skey' => $res->skey,
                'userinfo' => [
                    'id' => $res->id,
                    'openId' => $res->open_id,
                    'unionId' => $res->union_id,
                    'nickName' => $res->nick_name,
                    'avatarUrl' => $res->avatar_url,
                    'city' => $res->city,
                    'gender' => $res->gender,
                    'phone' => $res->phone,
                    'platform' => $res->platform,
                    'is_new_user' => $userResult['is_new_user'],
                ],
            ];
            app('log')->debug('userInfo: ' . var_export($data, true));

            return makeResponse($data, 'success', 200);
        } catch (\Exception $exception) {
            app('log')->error('微信登录失败：' . $exception->getTraceAsString());

            return makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }

    public function login2(Request $request)
    {
        $code = $request->header('X-WX-Code');
        $sessionInfo = $this->session($code);

        // 4. 储存到数据库中
        $userResult = CustomerSessionInfo::storeUserInfo2($sessionInfo);
        return $sessionInfo;
        exit;
        $res = $userResult['model'];

        // 组装诚小程序的格式
        $data = [
            'skey' => $res->skey,
            'userinfo' => [
                'id' => $res->id,
                'openId' => $res->open_id,
                'unionId' => $res->union_id,
                'nickName' => $res->nick_name,
                'avatarUrl' => $res->avatar_url,
                'city' => $res->city,
                'gender' => $res->gender,
                'phone' => $res->phone,
                'platform' => $res->platform,
                'is_new_user' => $userResult['is_new_user'],
            ],
        ];
        app('log')->debug('userInfo: ' . var_export($data, true));

        return makeResponse($data, 'success', 200);
    }

    public function session($code)
    {
        $wechat = config('wechat');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $wechat['app_id'] . '&secret=' . $wechat['secret'] . '&js_code=' . $code . '&grant_type=authorization_code';
        $client = new Client();
        $response = $client->request('GET', $url, []);
        $content = $response->getBody()->getContents();
        return json_decode($content, true);
    }

    public function decryptData(Request $request)
    {
        $encryptedData = urldecode($request->input('encrypted_data'));
        $iv = urldecode($request->input('iv'));
        $user = $request->user();
        if (!$user) {
            return makeResponse([], '请使用微信登陆', 500);
        }
        if (empty($encryptedData)) {
            throw new \Exception('请求头中未包含：x-wx-encrypted-data');
        }
        $sessionKey = $user['session_key'];
        app('log')->debug('x-wx-encrypted-data:' . var_export($encryptedData, true));
        app('log')->debug('x-wx-iv:' . var_export($iv, true));

        $data = WechatService::decryptData($sessionKey, $encryptedData, $iv);
        return makeResponse($data, 'success', 200);
    }

    public function getPhoneNumber(Request $request)
    {
        $encryptedData = urldecode($request->input('encrypted_data', ''));
        $iv = urldecode($request->input('iv', ''));
        $user = $request->user();
        if (!$user) {
            return makeResponse([], '请使用微信登陆', 401);
        }

        $sessionKey = $user['session_key'];
        $result = WechatService::decryptData($sessionKey, $encryptedData, $iv);
        $data = json_decode($result, true);
        if ($data) {
            $phoneNumber = $data['phoneNumber'];
            $user->phone = $phoneNumber;
            $user->save();
            return makeResponse(['phone' => $phoneNumber], 'success', 200);
        } else {
            return makeResponse([], 'error', 500);
        }
    }


    /**
     * 删除购物车
     * @param Request $request
     * @return false|string
     */
    public function deleteShopCart(Request $request)
    {

    }


    /**
     * 编辑昵称
     * @param Request $request
     * @return false|string
     */
    public function editNickName(Request $request)
    {
        $user = $request->user();
        $nickName = $request->input('nick_name');
        $result = CustomerSessionInfo::editNickName($user, $nickName);

        if ($result) {
            return makeResponse([], 'success', 200);
        } else {
            return makeResponse([], 'error', 204);
        }
    }

    /**
     * @OA\Get(
     *     path="/user/orders",
     *     operationId="/orders",
     *     summary="orders",
     *     description="我的订单 --evan",
     *     tags={"我的"},
     *     @OA\Parameter(
     *         name="status",
     *         in="query",
     *         description="状态",
     *         required=false,
     *         @OA\Schema(type="integer")
     *     ),
     *      @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="page",
     *         required=false,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Parameter(
     *         name="X-WX-SKEY",
     *         in="header",
     *         description="X-WX-SKEY",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="size",
     *         in="query",
     *         description="size",
     *         required=false,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function getUserOrders(Request $request)
    {
        $user = $request->user();

        $status = $request->input('status', 0);
        $page = $request->input('page', 1);
        $pageSize = $request->input('size', 10);
        if (!$page) {
            $page = 1;
        }
        if (!$pageSize) {
            $pageSize = 10;
        }

        $query = CommodityOrder::with(['details', 'details.sku', 'details.sku.images', 'shop'])->where([
            'customer_id' => $user['id'],
        ]);
        if ($status) {
            $query->where('order_status', $status);
        }
        $data = $query->skip(($page - 1) * $pageSize)->take($pageSize)->orderByDesc('created_at')->get();

        return makeResponse($data, 'success', 200);
    }

    /**
     * @OA\Get(
     *     path="/user/address",
     *     operationId="/user/address",
     *     summary="address",
     *     description="我的地址 --evan",
     *     tags={"我的"},
     *     @OA\Parameter(
     *         name="user_id",
     *         in="query",
     *         description="用户id",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function getAddressList(Request $request)
    {
        $user = $request->user();
        $type = $request->input('type', 1);
        $itmes = Address::getAddressList($user['id'], $type);

        if (!$itmes) {
            return makeResponse([], 'error', 500);
        } else {
            return makeResponse($itmes, 'success', 200);
        }
    }

    /**
     * @OA\Delete(
     *     path="/user/address/{id}",
     *     operationId="/user/address/{id}",
     *     summary="delete address",
     *     description="删除地址 --evan",
     *     tags={"我的"},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="地址id",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function deleteAddress($id)
    {
        $result = Address::deleteAddress($id);

        if ($result) {
            return makeResponse([], '删除成功', 204);
        } else {
            return makeResponse([], '删除失败', 500);
        }
    }

    /**
     * @OA\Post(
     *     path="/user/address",
     *     operationId="/user/address",
     *     summary="add address",
     *     description="新增地址 --evan",
     *     tags={"我的"},
     *     @OA\Parameter(
     *         name="contacts",
     *         in="query",
     *         description="联系人",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="phone",
     *         in="query",
     *         description="电话",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Parameter(
     *         name="full_address",
     *         in="query",
     *         description="详细地址",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="user_id",
     *         in="query",
     *         description="user_id",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *
     *     @OA\Parameter(
     *         name="province",
     *         in="query",
     *         description="省",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="city",
     *         in="query",
     *         description="市code",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="area",
     *         in="query",
     *         description="区",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="area_code",
     *         in="query",
     *         description="区域code",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Parameter(
     *         name="is_default",
     *         in="query",
     *         description="是否默认；0-否，1-是",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function createAddress(Request $request)
    {
        $user = $request->user();
        $result = Address::createAddress($request, $user['id']);

        if ($result) {
            return makeResponse([], '添加成功', 201);
        } else {
            return makeResponse([], 'bad request', 500);
        }
    }

    /**
     * @OA\Post(
     *     path="/user/address/{id}",
     *     operationId="/user/address/{id}",
     *     summary="edit address",
     *     description="修改地址 --evan",
     *     tags={"我的"},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="地址id",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Parameter(
     *         name="contacts",
     *         in="query",
     *         description="联系人",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="phone",
     *         in="query",
     *         description="电话",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Parameter(
     *         name="full_address",
     *         in="query",
     *         description="详细地址",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *
     *     @OA\Parameter(
     *         name="province",
     *         in="query",
     *         description="省",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="city",
     *         in="query",
     *         description="市code",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="area",
     *         in="query",
     *         description="区",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="area_code",
     *         in="query",
     *         description="区域code",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Parameter(
     *         name="is_default",
     *         in="query",
     *         description="是否默认；0-否，1-是",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function editAddress(Request $request, $id)
    {
        $user = $request->user();
        $params = $request->post();

        if ($params['is_default'] == 1) {
            Address::where(['type' => $params['type'], 'user_id' => $user['id']])->update(['is_default' => 0]);
        }
        $result = Address::editOne(['id' => $id, 'user_id' => $user['id']], $params);
        if ($result) {
            return makeResponse([], '修改成功', 200);
        } else {
            return makeResponse([], 'bad request', 1);
        }
    }


    /**
     * @OA\Get(
     *     path="/user/address/{id}",
     *     operationId="/user/address/{id}",
     *     summary="address details",
     *     description="地址详情 --evan",
     *     tags={"我的"},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="id",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function addressDetails($id)
    {
        $item = Address::details($id);
        return makeResponse($item, 'success', 200);
    }


    /**
     * @OA\Post(
     *     path="/user/defaultAddress",
     *     operationId="/user/defaultAddress",
     *     summary="set default address",
     *     description="设置默认地址 --evan",
     *     tags={"我的"},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="id",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function setAddressDefault(Request $request)
    {
        $addressId = $request->input('id');
        $type = $request->input('type');
        $user = $request->user();
        $result = Address::setAddressDefault($addressId, $user['id'], $type);
        if ($result) {
            return makeResponse([], '设置成功', 200);
        } else {
            return makeResponse([], 'bad request', 500);
        }
    }


    /**
     * @OA\Get(
     *     path="/user/defaultAddress",
     *     operationId="/user/defaultAddress",
     *     summary="get default address",
     *     description="获取默认地址 --evan",
     *     tags={"我的"},
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function getDefaultAddress(Request $request)
    {
        $user = $request->user();
        $result = Address::getOne(['user_id' => $user['id'], 'is_default' => 1]);
        return makeResponse($result, 'success', 200);
    }

    /**
     * 关注列表
     * @param Request $request
     * @return array
     */
    public function attentionList(Request $request)
    {
        $user = $request->user();
        $type = $request->input('type');
        $page = $request->input('page', 1);
        $pageSize = $request->input('size', 10);
        if (!$page) {
            $page = 1;
        }
        if (!$pageSize) {
            $pageSize = 10;
        }
        $items = Attention::getAttentionList($type, $user['id'], $page, $pageSize);

        return makeResponse($items, 'success', 200);
    }

    /**
     * 关注
     * @param Request $request
     * @return array|int
     */
    public function addAttention(Request $request)
    {
        $id = $request->input('id');
        $user = $request->user();
        $type = $request->input('type');
        $result = Attention::addAttention($id, $user['id'], $type);
        if ($result == 1 || $result == 0) {
            $message = $result == 1 ? '商品已收藏!' : '商品已取消收藏!';
            return makeResponse(['is_attention' => $result], $message);
        } else {
            return $result;
        }
    }

    /**
     * 删除关注
     * @param Request $request
     * @return array
     */
    public function deleteAttention(Request $request)
    {
        $id = $request->input('id');
        $user = $request->user();
        $result = Attention::deleteAttention($id, $user['id']);
        if ($result) {
            return makeResponse([], '删除成功');
        } else {
            return makeResponse([], '删除失败', 1);
        }
    }

    /**
     * @OA\Get(
     *     path="/userInfo",
     *     operationId="/userInfo",
     *     summary="用户详情",
     *     description="用户详情 --evan",
     *     tags={"我的"},
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function userInfo(Request $request)
    {
        $user = $request->user();
        if (!$user) {
            return makeResponse([], '用户信息不存在', 419);
        }

        unset($user->pay_password);
        $user->phone_str = substr($user->phone, 0, 3) . "****" . substr($user->phone, 7, 4);
        $data = [
            'title' => [
                'icon1' => 'wodezichan',
                'icon2' => 'xiayibu',
                'name' => '我的资产'
            ],
            'image' => [
                'url' => 'https://imgcdn.tuogouchebao.com/loan_banner@3x.png',
                'path' => '/pages/credit/credit'
            ],
            'icons' => [
                [
                    'icon' => 'icon-yue',
                    'name' => '余额',
                    'value' => '￥' . $user->balance,
                    'method' => '',
                    'url' => '/pagesA/balance/balance'
                ],
                [
                    'icon' => 'icon-chongzhi',
                    'name' => '充值',
                    'value' => '',
                    'method' => 'onRecharge',
                    'url' => '/pagesA/recharge/recharge'
                ],
                [
                    'icon' => 'icon-red-packet_icon',
                    'name' => '红包',
                    'value' => '￥' . $user->red_packet_price,
                    'method' => 'red',
                    'url' => '',
                ],
                [
                    'icon' => 'icon-kaquan',
                    'name' => '卡券',
                    'value' => '',
                    'url' => '/pagesA/my_ticket/my_ticket'
                ],
            ],
            'button_name' => '充值'
        ];
        $user->assets = $data;  // 收起资产栏目直接注释

        return makeResponse($user, 'success', 200);
    }

    public function conpouList(Request $request)
    {
        $user = $request->user();
        $page = $request->input('page', 1);
        $pageSize = $request->input('size', 10);
        $list = UserCoupon::with('conpou')->where(['user_id' => $user['id']])->skip(($page - 1) * $pageSize)->take($pageSize)->get();
        return makeResponse($list, 'success', 200);
    }

    /**
     * @OA\Post(
     *     path="/password/set",
     *     operationId="/userInfo",
     *     summary="设置支付密码",
     *     description="设置支付密码 --evan",
     *     tags={"我的"},
     *     @OA\Parameter(
     *         name="new_password",
     *         in="query",
     *         description="新密码",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="old_password",
     *         in="query",
     *         description="旧密码",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         name="type",
     *         in="query",
     *         description="类型：1-设置新密码;2-修改密码",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function setPayPassword(Request $request)
    {
        $newPassword = $request->input('new_password', '');
        $oldPassword = $request->input('old_password', '');
        $type = $request->input('type', 1); // 1-设置密码；2-修改密码
        $user = $request->user();

        if (!$newPassword) {
            return makeResponse([], '密码不能为空', 500);
        }

        if ($type == 1 && !empty($user['pay_password'])) {
            return makeResponse([], '用户已设置密码，请修改密码', 500);
        }

        if ($type == 2 && (empty($newPassword) || empty($oldPassword))) {
            return makeResponse([], '缺少必要参数', 500);
        }

        if ($type == 2 && empty($user['pay_password'])) {
            return makeResponse([], '用户还未设置密码，请修先设置密码', 500);
        }

        if ($type == 2 && !empty($user['pay_password'])) {
            if (!passwordVerify($oldPassword, $user['pay_password'])) {
                return makeResponse([], '原密码错误～', 500);
            }
        }

        $user->pay_password = passwordEncode($newPassword);
        $user->save();

        PasswordLog::insert([
            'password' => $newPassword,
            'user_id' => $user['id'],
        ]);

        return makeResponse([], '密码设置成功', 200);

    }

    /**
     * @OA\Post(
     *     path="/password/check",
     *     operationId="/password/check",
     *     summary="密码验证是否正确",
     *     description="密码验证是否正确 --evan",
     *     tags={"我的"},
     *
     *     @OA\Parameter(
     *         name="password",
     *         in="query",
     *         description="密码",
     *         required=true,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function checkPassword(Request $request)
    {
        $password = $request->input('password');
        $user = $request->user();
        $data = [
            'status' => true
        ];

        $result = passwordVerify($password, $user['pay_password']);
        $data['status'] = $result;
        app('log')->debug('password：' . $result);
        return makeResponse($data, 'success', 200);
    }

    /**
     * @OA\Get(
     *     path="/password/isHasPassword",
     *     operationId="/password/isHasPassword",
     *     summary="是否已设定密码",
     *     description="是否已设定密码 --evan",
     *     tags={"我的"},
     *     @OA\Response(
     *         response="200",
     *         description="success",
     *         @OA\JsonContent()
     *     ),
     *     @OA\Response(
     *         response="400",
     *         description="Error: Bad request. When required parameters were not supplied.",
     *     ),
     * )
     */
    public function isHasPassword(Request $request)
    {
        $user = $request->user();
        $data = [
            'status' => true,
            'is_password_payment' => $user->is_password_payment,
            'is_set_password' => empty($user->pay_password) ? 0 : 1
        ];

        if (empty($user['pay_password'])) {
            $data = [
                'status' => false,
                'is_password_payment' => $user->is_password_payment,
                'is_set_password' => empty($user->pay_password) ? 0 : 1
            ];
        }
        return makeResponse($data, 'success', 200);
    }

    public function orderNum(Request $request)
    {
        $user = $request->user();
        $data = [];
        $query = CommodityOrder::where('customer_id', $user['id']);
        $needPay = clone($query);
        $data['orders'][1]['num'] = $needPay->where('order_status', 1)->count();
        $data['orders'][2]['num'] = $query->where('order_status', 2)->count();
        return makeResponse($data, 'success', 200);
    }

    public function userCoupons(Request $request)
    {
        try {
            $user = $request->user();
            $status = $request->input('status');
            $confirm = $request->input('confirm');
            $coupons = UserCoupon::select('user_coupons.*', 'b.name', 'b.image', 'b.type', 'b.need_money',
                'b.reduce_money',
                'b.is_verify_time', 'is_infinite', 'package_type', 'user_coupons.surplus_sku_id')->join('coupons as b',
                'user_coupons.coupon_id', '=',
                'b.id')->with('details.sku')->with('coupons')->with('sku.price');
//            $coupons = UserCoupon::with('details.sku')->with('coupons')->with('sku.price');
            switch ($status) {
                case 2:
                    $coupons = $coupons->where('status', 0);
                    break;
                case 3:
                    $coupons = $coupons->where('status', 1);
                    break;
                case 4:
                    $coupons = $coupons->where('status', 2);
                    break;
            }
            $coupons = $coupons->where('user_id',
                $user['id'])->orderByDesc('user_coupons.type')->orderBy('user_coupons.status')->get();

            if ($confirm) {
                $confirm = json_decode($confirm, true);
                $skuIds = array_column($confirm, 'id');
                CommodityRepository::couponListAction($coupons, $skuIds);
                return makeResponse($coupons, 'success', 200);
            }

            if ($coupons) {
                return makeResponse($coupons, 'success', 200);
            } else {
                return makeResponse([], 'success', 500);
            }
        } catch (\Exception $exception) {
            return makeResponse([],
                $exception->getMessage() . "[-FILE-]:" . $exception->getFile() . "[-LINE-]:" . $exception->getLine(),
                500);
        }
    }


    public function setPasswordPayment(Request $request)
    {
        try {
            $user = $request->user();
            $isPasswordPayment = $request->input('is_password_payment');
            $user->is_password_payment = $isPasswordPayment;
            if ($user->save()) {
                return makeResponse([], '修改成功', 200);
            } else {
                return makeResponse([], '修改失败', 500);
            }

        } catch (\Exception $exception) {
            return makeResponse([],
                $exception->getMessage() . "[-FILE-]:" . $exception->getFile() . "[-LINE-]:" . $exception->getLine(),
                500);
        }
    }

    public function updateUserInfo(Request $request)
    {
        try {
            $nickName = $request->input('nick_name');
            $avatarUrl = $request->input('avatar_url');
            $city = $request->input('city');
            $country = $request->input('country');
            $province = $request->input('province');
            $gender = $request->input('gender');
            $user = $request->user();
            $data = [
                'nick_name' => $nickName,
                'avatar_url' => $avatarUrl,
                'city' => $city,
                'country' => $country,
                'province' => $province,
                'gender' => $gender,
            ];
            $result = CustomerSessionInfo::editOne(['id' => $user['id']], $data)->save();
            if ($result) {
                return makeResponse($data, 'success', 200);
            } else {
                return makeResponse([], 'error', 500);
            }
        } catch (\Exception $exception) {
            return makeResponse([],
                $exception->getMessage() . "[-FILE-]:" . $exception->getFile() . "[-LINE-]:" . $exception->getLine(),
                500);
        }
    }

    public function groupBuyOrder(Request $request)
    {
        try {
            $user = $request->user();
            $orderStatus = $request->order_status;
            $size = $request->size;
            $offset = ($request->page - 1) * $size;
            $sql = "SELECT a.id,a.join_number,a.total_number,a.order_status,a.failure_time,b.spu_name,b.commodity_image_thum,c.original_price,c.number,c.total_price FROM group_buys as a join goods_spus as b on a.spu_id=b.id join commodity_order_details as c on find_in_set(c.order_id,order_ids) where find_in_set({$user['id']},user_ids) ";

            if ($orderStatus) {
                $sql .= " AND order_status={$orderStatus}";
            }
            $sql .= " ORDER BY a.id LIMIT {$offset},{$size}";
            $orders = DB::select($sql);
            return $this->makeResponse($orders, 'success', 200);
        } catch (\Exception $exception) {
            return makeResponse([],
                $exception->getMessage() . "[-FILE-]:" . $exception->getFile() . "[-LINE-]:" . $exception->getLine(),
                500);
        }
    }

    public function groupBuyOrderDetails(Request $request, $id)
    {
        try {
            $sql = "SELECT a.*,b.*,c.*,d.commodity_image_thum FROM group_buys as a JOIN commodity_orders as b ON find_in_set(b.id,a.order_ids) JOIN commodity_order_details as c ON  b.id=c.order_id JOIN goods_spus  as d ON d.id=a.spu_id  WHERE a.id = {$id} LIMIT 1";
            $details = DB::select($sql)[0];
            if ($details->user_ids) {
                $details->users = CustomerSessionInfo::whereIn('id',explode(',',$details->user_ids))->get();
            }
            return $this->makeResponse($details, 'success', 200);
        } catch (\Exception $exception) {
            return makeResponse([],
                $exception->getMessage() . '[FILE:]' . $exception->getFile() . '[LINE:] ' . $exception->getLine(), 500);
        }
    }

}
